package com.monkey.core.plugin.report.excel;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 导出Excel的模板对象
 */
public class ExcelTemplate {

    private List<HSSFCell> parameterCells = new ArrayList<>();
    private List<HSSFCell> fieldCells = new ArrayList<>();
    private List<HSSFCell> variableCells = new ArrayList<>();
    private HSSFWorkbook workbook;

    public ExcelTemplate(HSSFWorkbook workbook) {
        Assert.notNull(workbook, "workbook can not is null");
        this.workbook = workbook;
        parse();
    }

    /**
     * 解析Excel模板
     */
    private void parse() {
        HSSFSheet sheet = workbook.getSheetAt(0);
        Assert.notNull(sheet, "模板工作表对象不能为空!");

        for (int k = 0; k < sheet.getLastRowNum() + 1; k++) {
            HSSFRow cells = sheet.getRow(k);
            for (int j = 0; j < cells.getLastCellNum() + 1; j++) {
                HSSFCell cell = cells.getCell(j);
                if (cell == null) {
                    continue;
                }

                String cellContent = cell.getStringCellValue();
                if (StringUtils.isEmpty(cellContent)) {
                    continue;
                }

                if (cellContent.contains("$P") || cellContent.contains("$p")) {
                    parameterCells.add(cell);
                } else if (cellContent.contains("$F") || cellContent.contains("$f")) {
                    fieldCells.add(cell);
                } else if (cellContent.contains("$V") || cellContent.contains("$v")) {
                    variableCells.add(cell);
                }
            }
        }
    }

    /**
     * 增加一个参数对象
     */
    public void addParameterCell(HSSFCell cell) {
        parameterCells.add(cell);
    }

    /**
     * 增加一个字段对象
     */
    public void addFieldCell(HSSFCell cell) {
        fieldCells.add(cell);
    }

    public HSSFWorkbook getWorkbook() {
        return workbook;
    }

    public List<HSSFCell> getParameterCells() {
        return parameterCells;
    }

    public List<HSSFCell> getFieldCells() {
        return fieldCells;
    }

    public List<HSSFCell> getVariableCells() {
        return variableCells;
    }
}
